/**
 * MenuEdit
 * @authors 杨兴洲（of2502）
 * @date    2017/5/31 0031 19:26
 * @version 1.0
 * @last-modify  杨兴洲（of2502）
 */

import React, { Component } from 'react';
import { Relax } from 'iflux2';
import { Button, Form, Radio, Input, Modal, message } from 'antd';
import { Map, List, fromJS } from 'immutable';
import MassInput from 'uikit/mass-input';
import GaUtil from "util/ga-util";
const RadioGroup = Radio.Group;
const FormItem = Form.Item;

const TABS = {
    msg: ["text", "mpnews", "news", "image"],
    link: ["page"]
};

@Relax
export default class MenuEdit extends Component {
    static defaultProps = {
        selectedIndex: -1,
        selectedSubIndex: -1,
        button: List(),
        saveMenu: () => void 0,
        updateSubItem: () => void 0,
        updateItem: () => void 0,
        deleteItem: () => void 0,
        deleteSubItem: () => void 0,
        getImageDetail: () => void 0,
        getMPNewsDetail: () => void 0,
        getNewsDetail: () => void 0,
    };

    constructor(props) {
        super(props);
        const { } = this.props;
        let data = this.getItemData();
        const type = data.get("type") || "text";

        let tempData = {
            type,
            data: null
        };
        let selectedTab = "link";
        // console.log(tempData.type, selectedTab);
        this.state = {
            temp: {},
            tempData: {
                type: type,
                data: null
            },
            tabs: TABS[selectedTab], // TABS[selectedTab]
            selectedTab: selectedTab
        };
    }

    getSelectedState = (nextProps) => {
        const { selectedIndex, selectedSubIndex } = nextProps || this.props;
        const noSelected = selectedIndex < 0;
        let selectedState = "noSelected";
        if (selectedIndex >= 0 && selectedSubIndex >= 0) selectedState = "sub";
        if (selectedIndex >= 0 && selectedSubIndex < 0) selectedState = "main";
        return selectedState;
    };


    componentWillReceiveProps(nextProps) {
        this.updateEdit(nextProps)
    }

    getItemData = (nextProps) => {
        const { selectedIndex, selectedSubIndex, button } = nextProps || this.props;
        let selectedState = this.getSelectedState(nextProps);
        let data = Map();
        if (selectedState === "sub") {
            data = button.getIn([selectedIndex, "sub_button", selectedSubIndex]);
        } else if (selectedState === "main") {
            data = button.get(selectedIndex);
        }
        return data;
    };
    updateEdit = async (nextProps) => {

        // let {tempData, selectedTab} = this.state;
        let tempData = {}, selectedTab = "";
        let data = this.getItemData(nextProps);

        const type = data.get("type") || "text";
        if (type === "view") {
            tempData.type = "page";
            tempData.data = {
                type: "custom",
                data: {
                    url: data.get("url")
                }
            };
            selectedTab = "link";
            tempData.tabs = TABS[selectedTab];
            setTimeout(() => {
                this.refs.mediaEditor.update(tempData);
            }, 1);
            // 无法绑定链接.todo
        }
        if (type === "click") {
            const key = data.get("key");
            if (key.split("__")[0] === "text") {
                tempData.type = "text";
                tempData.data = key.split("__")[1];
                // console.log(tempData);
            }
            if (key.split("__")[0] === "news") {
                tempData.type = "news";
                let result = await this.props.getNewsDetail(key.split("__")[1]);
                // 查询高级图文详情
                tempData.data = {
                    id: key.split("__")[1],
                    articles: result.articles
                }
            }
            selectedTab = "msg";
            tempData.tabs = TABS[selectedTab];
            setTimeout(() => {
                this.refs.mediaEditor.update(tempData);
            }, 1);
        }
        if (type === "media_id") {
            // todo:查询后端接口,判断类型
            let result = await this.props.getMPNewsDetail(data.get("media_id"));
            if (result.news_item) {
                tempData.type = "mpnews";
                tempData.data = {
                    content: result,
                    media_id: data.get("media_id")
                };
            } else {
                try {
                    tempData.type = "image";
                    let result2 = await this.props.getImageDetail(data.get("media_id"));
                    tempData.data = { ...result2 }
                } catch (err) {
                    console.log(err)
                }
            }
            // console.log(tempData);
            selectedTab = "msg";
            tempData.tabs = TABS[selectedTab];
            setTimeout(() => {
                this.refs.mediaEditor.update(tempData);
            }, 1);
        }
        // console.log("tempData", tempData, selectedTab);
        this.setState({
            tempData,
            selectedTab
        });
    };

    /*高级图文： click类型*/
    render() {
        const { button } = this.props;
        const { tempData } = this.state;
        // this.updateEdit();
        let data = this.getItemData();
        let selectedState = this.getSelectedState();

        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 14 },
        };

        // console.log("----------------", tempData);
        const ContentEditor = (
            // ['text', 'mpnews', 'news', 'image', 'voice', 'mpvideo', 'page']
            <div style={{ width: "65%", minWidth: 400, margin: "0 auto" }}>
                <MassInput
                    ref="mediaEditor"
                    textMaxLength={60}
                    tabs={this.state.tabs}
                    data={tempData} onChange={({ type, data }) => {
                        // console.log({ type, data });
                        if (!data) return;
                        let update = () => void 0;
                        if (selectedState === "sub") {
                            update = this.props.updateSubItem
                        } else if (selectedState === "main") (
                            update = this.props.updateItem
                        );

                        if (type === "mpnews" || type === "image") {
                            update({
                                type: "media_id",
                                media_id: data.media_id
                            });
                        }
                        if (type === "text") {
                            update({
                                type: "click",
                                key: `text__${data}`
                            });
                        }
                        if (type === "news") {
                            update({
                                type: "click",
                                key: `news__${data.id}`
                            });
                        }
                        if (type === "page") {
                            update({
                                type: "view",
                                url: data.data.url
                            });
                        }
                    }} />
            </div>
        );
        if (selectedState === "noSelected") return (<div/>);
        if (selectedState === "sub") return (
            <div className="wx-menu-edit">
                <div className="wx-menu-edit-panel">
                    <div className="panel-header">
                        <h3>{data.get("name")}</h3>
                        <a className="btn-link" href="javascript:;" onClick={this.deleteSubItem}>删除子菜单</a>
                    </div>
                    <div className="panel-content">
                        <Form >
                            <FormItem style={{ marginTop: 20, marginBottom: 0 }} {...formItemLayout}
                                label={<span>菜单名称&nbsp;</span>}>
                                <Input placeholder="字数不超过8个汉字或16个字母" value={data.get("name")}
                                    onChange={this.changeSubTitle} />
                                <span style={{ fontSize: "12px", color: "#9d9d9d" }}>字数不超过8个汉字或16个字母</span>
                            </FormItem>
                            <FormItem  {...formItemLayout}
                                label={<span>菜单内容&nbsp;</span>}>
                                <RadioGroup onChange={this.changeSubType} value={this.state.selectedTab}>
                                    <Radio value="msg">发送消息</Radio>
                                    <Radio value="link">网页跳转</Radio>
                                </RadioGroup>
                            </FormItem>
                            {ContentEditor}
                        </Form>
                    </div>
                </div>
                <div className="wx-menu-edit-control">
                    {/*<Button>预览</Button>*/}
                    <Button type="primary" onClick={this.saveMenu}>保存并发送</Button>
                </div>
            </div>
        );
        return (
            <div className="wx-menu-edit">
                <div className="wx-menu-edit-panel">
                    <div className="panel-header">
                        <h3>{data.get("name")}</h3>
                        <a className="btn-link" onClick={this.deleteItem} href="javascript:;">删除菜单</a>
                    </div>

                    <div className="panel-content">
                        <Form >
                            <FormItem style={{ marginTop: 20, marginBottom: 0 }} {...formItemLayout}
                                label={<span>菜单名称&nbsp;</span>}>
                                <Input placeholder="字数不超过4个汉字或8个字母" value={data.get("name")}
                                    onChange={this.changeTitle} />
                                <span style={{ fontSize: "12px", color: "#9d9d9d" }}>字数不超过4个汉字或8个字母</span>
                            </FormItem>
                            {
                                !(data.get("sub_button") && data.get("sub_button").size > 0) && (
                                    <FormItem  {...formItemLayout}
                                        label={<span>菜单内容&nbsp;</span>}>
                                        <RadioGroup onChange={this.changeSubType} value={this.state.selectedTab}>
                                            <Radio value="msg">发送消息</Radio>
                                            <Radio value="link">网页跳转</Radio>
                                        </RadioGroup>
                                    </FormItem>
                                )
                            }
                            {
                                !(data.get("sub_button") && data.get("sub_button").size > 0) && ContentEditor
                            }
                        </Form>
                    </div>
                </div>
                <div className="wx-menu-edit-control">
                    {/*<Button>预览</Button>*/}
                    <Button type="primary" onClick={this.saveMenu}>保存并发送</Button>
                </div>
            </div>
        )
    }

    saveMenu = () => {
        // check menu
        if (!this.checkMenu()) return false;
        this.props.saveMenu().then(data => {
            message.success('更新菜单成功');
        });
        GaUtil.addEvent({eventAction:"保存菜单", eventLabel:"自定义菜单"})
    };

    checkMenu = () => {
        const { button } = this.props;

        return button.toJS().every((item, index) => {
            if (!item.name) {
                message.error('菜单标题不全');
                return false;
            }
            if (getBLen(item.name) > 8) {
                message.error(`菜单标题【${item.name}】名称过长`);
                return false;
            }
            // 无子菜单
            if (!item.sub_button || !item.sub_button.length > 1) {
                if (!item.type) {
                    message.error('菜单标题不全');
                    return false;
                } else {
                    if (item.type === "media_id" && !item.media_id) {
                        message.error('菜单未选择素材');
                        return false;
                    } else if (item.type === "view" && !item.url) {
                        message.error('菜单未选择链接');
                        return false;
                    } else if (item.type === "click" && !item.key) {
                        message.error('菜单未选择素材');
                        return false;

                    } else {
                        return true;
                    }
                }
            }

            // 检查子菜单
            return item.sub_button.every((subItem, subIndex) => {
                if (!subItem.name) {
                    message.error('子菜单标题不全');
                    return false;
                }
                if (getBLen(subItem.name) > 16) {
                    message.error(`子菜单标题【${subItem.name}】名称过长`);
                    return false;
                }
                if (!subItem.type) {
                    message.error('子菜单标题不全');
                    return false;
                } else {
                    if (subItem.type === "media_id" && !subItem.media_id) {
                        message.error('子菜单未选择素材');
                        return false;
                    } else if (subItem.type === "view" && !subItem.url) {
                        message.error('子菜单未选择链接');
                        return false;
                    } else if (subItem.type === "click" && !subItem.key) {
                        message.error('子菜单未选择素材');
                        return false;
                    } else {
                        return true;
                    }
                }
            });


        });
    };

    changeSubTitle = (e) => {
        this.props.updateSubItem({ name: e.target.value });
    };

    checkSubTitle = (e) => {
        if (getBLen(e.target.value) > 16) {
            message.warn("子菜单名称不能超过8个汉字或16个字符");
            return false;
        }
        return true;
    };

    changeSubType = (e) => {
        // console.log(e.target.value);
        this.setState({
            selectedTab: e.target.value, //"msg" // "link"
            tabs: TABS[e.target.value]
        });
        this.refs.mediaEditor.update({ tabs: TABS[e.target.value] });

        // this.props.updateSubItem({type: e.target.value});
    };

    changeTitle = (e) => {
        this.props.updateItem({ name: e.target.value });
    };
    checkTitle = (e) => {
        if (getBLen(e.target.value) > 8) {
            message.warn("菜单名称不能超过4个汉字或8个字符");
            return false;
        }
        return true;
    };

    changeType = (e) => {
        this.setState({
            selectedTab: e.target.value, //"msg" // "link"
            tabs: TABS[e.target.value]
        });
        this.refs.mediaEditor.update({ tabs: TABS[e.target.value] });
        this.props.updateItem({ type: e.target.value });
    };

    deleteItem = () => {
        Modal.confirm({
            title: `是否确定删除该菜单?`,
            onOk: this.props.deleteItem
        });
    };
    deleteSubItem = () => {
        Modal.confirm({
            title: `是否确定删除该子菜单?`,
            onOk: this.props.deleteSubItem
        });
    }
}

/**
 * 获取字符串长度（汉字2,数字字母1）
 * @param str
 * @returns {*}
 */
function getBLen(str) {
    if (str === null) return 0;
    if (typeof str !== "string") {
        str += "";
    }
    return str.replace(/[^\x00-\xff]/g, "01").length;
}